package middlewares

import (
	"context"
	"net/http"
	"sdn-executor/utils/erros"
	"time"

	"github.com/gin-gonic/gin"
)

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE, HEAD, PATCH")
			c.Header("Access-Control-Allow-Headers", "*")
			c.Header("Access-Control-Allow-Credentials", "true")
		}
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

// JSONResponse 返回 JSON 格式数据中间件。默认返回 JSON 格式数据，也可在业务代码中自定义返回格式。
func JSONResponse() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Content-Type", "application/json")
		c.Next()
	}
}

func HandleTimeout(timeout time.Duration) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 为请求创建一个带超时的上下文
		ctx, cancel := context.WithTimeout(c.Request.Context(), timeout)
		defer cancel()

		// 将新建的上下文设置为请求上下文
		c.Request = c.Request.WithContext(ctx)

		// 创建用于检测超时的通道
		finished := make(chan struct{})
		go func() {
			// 执行下一个中间件或处理程序
			c.Next()
			close(finished)
		}()

		// 监听上下文的 Done 通道和处理完成的通道
		select {
		case <-ctx.Done():
			// 如果上下文完成，意味着超时发生
			c.AbortWithStatusJSON(http.StatusGatewayTimeout, erros.ProcessTimeout)
		case <-finished:
			// 正常完成
		}
	}
}
